package com.ly.lypopupwindowdemo.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.webkit.WebView;
import android.widget.ScrollView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * <p/>
 * bitmap工具类
 *
 * @author xiaruri
 */
public class BitmapUtils {

    /**
     * 裁剪圆形图片
     *
     * @param bitmap
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {

        return getRoundedRectangleBitmap(bitmap, 2);
    }

    public static Bitmap toRoundBitmap(Drawable drawable) {
        try {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            return toRoundCorner(bitmap);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取圆角位图的方法
     *
     * @param bitmap 需要转化成圆角的位图
     * @return 处理后的圆角位图
     */
    public static Bitmap toRoundCorner(Bitmap bitmap) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_4444);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = 90;
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    /**
     * 裁剪圆角矩形图片
     *
     * @param bitmap
     * @param ratio  圆角半径占图片最短边比例的倒数，为2时裁剪的图片为圆
     * @return
     */
    public static Bitmap getRoundedRectangleBitmap(Bitmap bitmap, float ratio) {

        if (bitmap != null && !bitmap.isRecycled()) {

            int width = bitmap.getWidth();
            int height = bitmap.getHeight();

            float roundPx;
            float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;

            if (width <= height) {
                roundPx = width / ratio;
                top = 0;
                bottom = width;
                left = 0;
                right = width;
                height = width;
                dst_left = 0;
                dst_top = 0;
                dst_right = width;
                dst_bottom = width;
            } else {
                roundPx = height / ratio;
                float clip = (width - height) / 2;
                left = clip;
                right = width - clip;
                top = 0;
                bottom = height;
                width = height;
                dst_left = 0;
                dst_top = 0;
                dst_right = height;
                dst_bottom = height;
            }

            Bitmap output = Bitmap
                    .createBitmap(width, height, Config.ARGB_4444);
            Canvas canvas = new Canvas(output);

            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect src = new Rect((int) left, (int) top, (int) right,
                    (int) bottom);
            final Rect dst = new Rect((int) dst_left, (int) dst_top,
                    (int) dst_right, (int) dst_bottom);
            final RectF rectF = new RectF(dst);

            paint.setAntiAlias(true);

            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, src, dst, paint);
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
            return output;
        }

        return null;
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = null;
        if (drawable != null) {
            bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
                                    : Config.RGB_565);

            Canvas canvas = new Canvas(bitmap);

            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
        }

        return bitmap;
    }

    /**
     * 获取scrollView的截图
     *
     * @param scrollView
     * @return
     */
    public static Bitmap getBitmapByScrollview(ScrollView scrollView) {
        Bitmap bitmap = null;

        if (scrollView != null) {
            int height = 0;
            // 获取实际高度
            for (int i = 0; i < scrollView.getChildCount(); i++) {
                height += scrollView.getChildAt(i).getHeight();
            }

            if (scrollView.getWidth() > 0 && height > 0) {
                bitmap = Bitmap.createBitmap(scrollView.getWidth(), height, Config.RGB_565);
                Canvas canvas = new Canvas(bitmap);
                scrollView.draw(canvas);
            }
        }

        return bitmap;
    }

    /**
     * 获取WebView的截图
     *
     * @param webView
     * @return
     */
    public static Bitmap getBitmapByWebView(WebView webView) {
        Bitmap bitmap = null;
        if (webView != null) {
            Picture snapShot = webView.capturePicture();
            if (snapShot.getWidth() > 0 && snapShot.getHeight() > 0) {
                bitmap = Bitmap.createBitmap(
                        snapShot.getWidth(),
                        snapShot.getHeight(),
                        Config.RGB_565);
                Canvas canvas = new Canvas(bitmap);
                snapShot.draw(canvas);
            }
        }

        return bitmap;
    }

    /**
     * 根据路径获取图片角度
     *
     * @param path 图片路径
     * @return 图片角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;

        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return degree;
    }

    /**
     * 旋转图片
     *
     * @param angle  旋转角度
     * @param bitmap 图片
     * @return
     */
    public static Bitmap rotaingImage(int angle, Bitmap bitmap) {
        Bitmap resizedBitmap = null;
        if (bitmap != null) {
            Matrix matrix = new Matrix();
            matrix.postRotate(angle);
            resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        return resizedBitmap;
    }

    /**
     * 根据路径获取对应的缩略图片
     *
     * @param path
     * @return
     */
    public static Bitmap getBitmapByPathAndScale(String path, int scale) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = scale;
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);

        return bitmap;
    }

    /**
     * Bitmap 是否可用
     *
     * @param bitmap
     * @return
     */
    public static boolean isAvailable(Bitmap bitmap) {
        return bitmap != null && !bitmap.isRecycled();
    }

    /**
     * 回收Bitmap
     *
     * @param bitmap
     */
    public static void recycle(Bitmap bitmap) {
        if (isAvailable(bitmap)) {
            try {
                bitmap.recycle();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 解析图片宽高
     *
     * @param context
     * @param resid
     * @return
     */
    public static int[] getDecodeBounds(Context context, int resid) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), resid, options);
        return new int[]{options.outWidth, options.outHeight};
    }

    /**
     * 将bitmap保存成文件
     *
     * @param bitmap
     * @param path
     */
    public static void saveBitmap2File(Bitmap bitmap, String path) {
        OutputStream outStream = null;
        ByteArrayOutputStream baos = null;
        try {
            File file = new File(path);
            if (!file.exists())
                file.createNewFile();
            if (bitmap.isRecycled()) {
                return;
            }
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] data = baos.toByteArray();

            outStream = new FileOutputStream(file);
            outStream.write(data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
    }
}
